﻿using System.Threading.Tasks;
using Wx.Standard.Base;
using Wx.Standard.Common;
using Wx.Standard.IService;
using Wx.Standard.Model.Self;
using Wx.Standard.Model.Send;

namespace Wx.Standard.Service
{
    public class SendModelMessage : ISendModelMessage
    {
        WxApi wxApi;
        internal SendModelMessage(WxApi wxApi)
        {
            this.wxApi = wxApi;
        }
        private SendModelMessage() { }
        bool ISendModelMessage.ModelMsg(ModelMessage msg)
        {
            var access_token = BaseClass.getAccessToken(wxApi.apiOption);
            var url = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}";
            var data = JsonHelper.modelToJson(msg).Replace("\"{", "{").Replace("}\"", "}").Replace(@"\", "");

            var str = BaseClass.postFormWechatService(data, url);
            var message = JsonHelper.jsonToModel<ErrorMessage>(str);
            return message.errcode == 0;
        }

        async Task<bool> ISendModelMessage.ModelMsgAsync(ModelMessage msg)
        {
            return await Task.Run<bool>(() =>
            {
                var access_token = BaseClass.getAccessToken(wxApi.apiOption);
                var url = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}";
                var data = JsonHelper.modelToJson(msg).Replace("\"{", "{").Replace("}\"", "}").Replace(@"\", "");

                var str = BaseClass.postFormWechatService(data, url);
                var message = JsonHelper.jsonToModel<ErrorMessage>(str);
                return message.errcode == 0;
            });
        }
    }
}